import markdown
import glob
import os
import re

p_mdlink = re.compile(r'\]\(\w+\.md(#\w+)?\)')

def cvtMDLinks(s):
    ''' convert [ALL2](ALL.md#ALL2) to [ALL2](ALL.html#ALL2).

        NOTE 1: only .md in link will be converted
        NOTE 2: the replacement is rather simple and straight, .md in
    '''
    ss = s
    for res in p_mdlink.finditer(s):
        rstr = res.group().replace('.md', '.html')
        ss = p_mdlink.sub(rstr, ss, 1)
        # print(res.group())
        # print(ss)
    return ss

def md2html(md_name, html_name):
    print(f"Converting {md_name} => {html_name}...")
    file_content = open(md_name, 'r', encoding='utf-8').read()
    r_content = cvtMDLinks(file_content)

    # 将Markdown转换为HTML
    html_content = markdown.markdown(r_content, extensions=['tables', 'fenced_code'])
    with open(html_name, 'w', encoding='utf-8') as file:
        file.write(html_content)

def batch_cvt(md_dir, html_dir):
    for md_name in glob.iglob(os.path.join(md_dir, "*.md")):
        _, md_fname = os.path.split(md_name)
        html_name = os.path.join(html_dir, md_fname[:-3]+'.html')

        md2html(md_name, html_name)

if __name__ == '__main__':
    md_dir = '../build/md'
    html_dir = '../build/html'
    batch_cvt(md_dir, html_dir)

    # s = '[ALL2](ALL.md#ALL2)   x=(a.md)  [FALU](FALU.md) x.md  [FFMA_RRU](Opcode_FFMA_RRU.md#FFMA__Encoding)'


